package javaguide.algorithm;

import java.util.Arrays;

public class BubbleSort {

    public static void main(String[] args) {
        int[] arr = {3, 5, 4, 7, 9, 1, 2, 6, 8};
        bubbleSort(arr);
        System.out.println("arr = " + Arrays.toString(arr));
    }

    public static void bubbleSort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            boolean flag = true;
            for (int j = 0; j < arr.length - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    flag = false;
                }
            }
            // 原数组已经排序好的时候，时间复杂度为O(n)
            if (flag) {
                break;
            }
        }
    }
}
